package com.xdf.ecommerce.service.impl;

import com.xdf.ecommerce.account.BalanceInfo;
import com.xdf.ecommerce.dao.EcommerceBalanceDao;
import com.xdf.ecommerce.entity.EcommerceBalance;
import com.xdf.ecommerce.filter.AccessContext;
import com.xdf.ecommerce.service.IBalanceService;
import com.xdf.ecommerce.vo.LoginUserInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * @author chanchaw
 * @create 2025-10-25 18:37
 */
@RequiredArgsConstructor
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class BalanceServiceImpl implements IBalanceService {
    private final EcommerceBalanceDao balanceDao;

    @Override
    public BalanceInfo getCurrentUserBalanceInfo() {
        LoginUserInfo loginUserInfo = AccessContext.getLoginUserInfo();
        EcommerceBalance balance = Optional.ofNullable(balanceDao.findByUserId(loginUserInfo.getId())).orElse(new EcommerceBalance());
        BalanceInfo ret = new BalanceInfo();
        ret.setUserId(loginUserInfo.getId());
        Long balance1 = Optional.ofNullable(balance.getBalance()).orElse(0L);
        ret.setBalance(balance1);
        return ret;
    }

    @Override
    public BalanceInfo deductBalance(BalanceInfo balanceInfo) {
        BalanceInfo currentUserBalanceInfo = getCurrentUserBalanceInfo();
        Long balance = currentUserBalanceInfo.getBalance() - balanceInfo.getBalance();
        if(balance.longValue() < 0) throw new RuntimeException("余额不足！");

        // 修改数据库数据
        LoginUserInfo loginUserInfo = AccessContext.getLoginUserInfo();
        EcommerceBalance ecBalance = balanceDao.findByUserId(loginUserInfo.getId());
        ecBalance.setBalance(balance);
        balanceDao.update(ecBalance);

        // 返回目标数据
        currentUserBalanceInfo.setBalance(balance);
        return currentUserBalanceInfo;
    }
}
